#include "HttpClientSingleton.h"

std::mutex HttpClientSingleton::mtx;

HttpClientSingleton& HttpClientSingleton::getInstance() {
    static HttpClientSingleton instance; // C++11 线程安全的静态局部变量
    return instance;
}

HttpClientSingleton::HttpClientSingleton() {
    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();
    if (!curl) {
        std::cerr << "CURL init failed!" << std::endl;
    }
}

HttpClientSingleton::~HttpClientSingleton() {
    if (curl) {
        curl_easy_cleanup(curl);
    }
    curl_global_cleanup();
}

size_t HttpClientSingleton::WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {
    ((std::string*)userp)->append((char*)contents, size * nmemb);
    return size * nmemb;
}

std::string HttpClientSingleton::postJson(const std::string& url, const std::string& jsonData) {
    std::lock_guard<std::mutex> lock(mtx); // 保证线程安全
    std::string response;

    if (curl) {
        struct curl_slist* headers = nullptr;
        headers = curl_slist_append(headers, "Content-Type: application/json");

        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        curl_easy_setopt(curl, CURLOPT_POST, 1L);
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonData.c_str());
        curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, jsonData.size());
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);

        CURLcode res = curl_easy_perform(curl);
        if (res != CURLE_OK) {
            std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
        }

        curl_slist_free_all(headers);
    }

    return response;
}


/*
 * 使用示例：
 * #include "HttpClientSingleton.h"
#include <iostream>

int main() {
    auto& client = HttpClientSingleton::getInstance();

    std::string url = "http://httpbin.org/post";
    std::string jsonData = R"({"name":"Bob","age":30})";

    std::string response = client.postJson(url, jsonData);
    std::cout << "Response: " << response << std::endl;

    return 0;
}

 *设计亮点
 * 线程安全：std::lock_guard<std::mutex> 确保多线程调用不出问题。
 * 全局唯一：getInstance() 返回静态局部变量，C++11 保证初始化线程安全。
 * 保留原有版本：你原来的 HttpClient 多例模式依旧可用，这个是单例专用版本。
 * 可随时扩展：以后你可以在里面加 get()、setHeader() 等功能，全局生效。
 *
 *
 * */